<template>
    <div style="text-align: center;margin: 0 20px">
        <div style="margin-top: 50px">
            <div style="font-size: 25px;font-weight: bold">注册新用户</div>
            <div style="font-size: 14px;color: grey">欢迎注册我们的学习平台，请在下方填写相关信息</div>
        </div>
        <div style="margin-top: 40px">
            <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
                <el-form-item prop="username">
                    <el-input v-model="form.username" :maxlength="8" type="text" placeholder="用户名">
                        <template #prefix>
                            <el-icon><User></User></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="form.password" :maxlength="16" type="password" placeholder="密码">
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password_repeat">
                    <el-input v-model="form.password_repeat" :maxlength="16" type="password" placeholder="重复密码">
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="phone">
                    <el-input v-model="form.phone" :maxlength="11" type="text" placeholder="电话号码">
                        <template #prefix>
                            <el-icon><Phone /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="address">
                    <el-input v-model="form.address" :maxlength="30" type="text" placeholder="居住地址">
                        <template #prefix>
                            <el-icon><HomeFilled /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input v-model="form.email" type="email" placeholder="电子邮件地址">
                        <template #prefix>
                            <el-icon><Message /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-row :gutter="10" style="width: 100%">
                        <el-col :span="17">
                            <el-input v-model="form.code" :maxlength="6" type="text" placeholder="请输入验证码">
                                <template #prefix>
                                    <el-icon><EditPen /></el-icon>
                                </template>
                            </el-input>
                        </el-col>
                        <el-col :span="5">
                            <el-button type="success" @click="validateEmail"
                                       :disabled="!isEmailValid || coldTime > 0">
                                {{coldTime > 0 ? '请稍后 ' + coldTime + ' 秒' : '获取验证码'}}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item prop="roleId">
                    <el-select v-model="form.roleId" clearable placeholder="选择身份">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-icon style="color: red;margin-left: 3px;" title="选择非客户身份需管理员认证后成功！"><Warning></Warning></el-icon>
                </el-form-item>
            </el-form>

        </div>
        <div style="margin-top: 40px">
            <el-button style="width: 270px" type="warning" @click="registerBefore" plain>立即注册</el-button>
        </div>
        <div style="margin-top: 20px">
            <span style="font-size: 14px;line-height: 15px;color: grey">已有账号? </span>
            <el-link type="primary" style="translate: 0 -2px" @click="router.push('/')">立即登录</el-link>
        </div>
        <div>
            <Vcode :show="isShow" @success="success" @close="close" @fail="fail"></Vcode>
        </div>
    </div>
</template>

<script setup>
import {EditPen, Lock, Message, User,Phone,HomeFilled,WarningFilled,Warning} from "@element-plus/icons-vue";
import router from "@/router";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {get, post} from "@/net";
//引入'vue3-puzzle-vcode'插件
import Vcode from 'vue3-puzzle-vcode'

//验证码模态框是否出现，默认不展示
const isShow = ref(false)
//用户点击遮罩层，关闭模态框
const close = () => {
    isShow.value = false
}
//用户通过了验证
const success = () => {
    isShow.value = false
    console.log('验证通过')
    register()
}

const registerBefore=()=>{
    formRef.value.validate((isValid) => {
        if (!isValid) {
            ElMessage.warning('请完整填写注册表单内容！')
        }else{
            isShow.value=true;
        }
    })

}
//用户验证失败
const fail = () => {
    console.log('验证失败')
}

const form = reactive({
    username: '',
    password: '',
    password_repeat: '',
    phone:'',
    address:'',
    email: '',
    code: '',
    roleId:''
})
const value = ref('')
const options = [
    {
        value: '2',
        label: '操作员',
    },
    {
        value: '3',
        label: '质检员',
    },
    {
        value: '4',
        label: '仓库管理员',
    },
    {
        value: '5',
        label: '销售员',
    },
    {
        value: '6',
        label: '客户',
    },
]
//用户名校验
const validateUsername = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)){
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
    } else {
        callback()
    }
}
//密码校验
const validatePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#%^&*])[a-zA-Z\d!@#%^&*]+$/.test(value)){
        callback(new Error("必须包括大小写英文字母、数字和符号"))
    }else if(value.length<6 |value.length>16){
        callback(new Error("密码必须在6~16位数之间"))
    }else if (value !== form.password) {
        callback(new Error("两次输入的密码不一致"))
    }else{
        callback()
    }
}
//重复密码校验
const validateRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    }else if (value !== form.password) {
        callback(new Error("两次输入的密码不一致"))
    }else{
        callback()
    }
}

const rules = {
    username: [
        { validator: validateUsername, trigger: ['blur'] },
        { min: 4, max: 8, message: '用户名的长度必须在4-12个字符之间', trigger: ['blur'] },
    ],
    password: [
        { validator: validatePassword, trigger: ['blur'] },
        //{ required: true, message: '请输入密码', trigger: 'blur' },
        //{ min: 6, max: 16, message: '密码的长度必须在6-16个字符之间', trigger: ['blur', 'change'] }
    ],
    password_repeat: [
        { validator: validateRePassword, trigger: ['blur'] },
        //{ required: true, message: '请再次输入密码', trigger: 'blur' },
    ],
    phone:[
        { required: true, message: '请输入电话号码', trigger: 'blur' },
    ],
    address:[
        { required: true, message: '请输入居住地址', trigger: 'blur' },
    ],
    email: [

        { required: true, message: '请输入邮件地址', trigger: 'blur' },
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur']}
    ],
    code: [
        { required: true, message: '请输入获取的验证码', trigger: 'blur' },
    ]
}

const formRef = ref()
const isEmailValid = ref(false)
const coldTime = ref(0)

const onValidate = (prop, isValid) => {
    if(prop === 'email')
        isEmailValid.value = isValid
}

const register = () => {
            post('/api/auth/register', {
                username: form.username,
                password: form.password,
                email: form.email,
                code: form.code,
                address:form.address,
                phone:form.phone,
                roleId:form.roleId
            }, () => {
                console.log('10086')
                console.log(form.roleId)
                if(form.roleId!=='6'){
                    ElMessage.warning('管理员通过后可登录')
                }else {
                    ElMessage.success('注册成功，欢迎加入我们')
                }
                router.push("/")
            })
}

const validateEmail = () => {
    ElMessage.info('正在发送邮件');
    coldTime.value = 60
    get(`/api/auth/ask-code?email=${form.email}&type=register`, () => {
        ElMessage.success(`验证码已发送到邮箱: ${form.email}，请注意查收`)
        const handle = setInterval(() => {
          coldTime.value--
          if(coldTime.value === 0) {
            clearInterval(handle)
          }
        }, 1000)
    }, undefined, (message) => {
        ElMessage.warning(message)
        coldTime.value = 0
    })
}
</script>

<style scoped>
</style>
